<script setup lang="ts">
/**
 * RSS阅读器首页组件
 * 包含RSS源列表、文章预览卡片、搜索功能等核心功能
 */

import { ref, computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { Search, Plus, RefreshCw, Settings, BookOpen, Star, Clock } from 'lucide-vue-next';
import { useRSSStore } from '@/stores/useRSSStore';
import type { Article, RSSFeed } from '@/types';

// 路由实例
const router = useRouter();

// RSS Store
const rssStore = useRSSStore();

// 响应式数据
const searchKeyword = ref('');
const isRefreshing = ref(false);

// 计算属性
const filteredArticles = computed(() => {
  if (!searchKeyword.value) {
    return rssStore.articles;
  }
  
  const keyword = searchKeyword.value.toLowerCase();
  return rssStore.articles.filter(article => 
    article.title.toLowerCase().includes(keyword) ||
    article.summary?.toLowerCase().includes(keyword) ||
    article.author?.toLowerCase().includes(keyword)
  );
});

const selectedFeed = computed(() => {
  return rssStore.feeds.find(feed => feed.id === rssStore.selectedFeedId);
});

const unreadCount = computed(() => {
  return rssStore.articles.filter(article => !article.isRead).length;
});

/**
 * 处理RSS源选择
 * @param {string | null} feedId - RSS源ID
 */
const handleFeedSelect = async (feedId: string | null) => {
  try {
    await rssStore.setSelectedFeed(feedId);
  } catch (error) {
    console.error('选择RSS源失败:', error);
  }
};

/**
 * 处理文章点击
 * @param {Article} article - 文章对象
 */
const handleArticleClick = (article: Article) => {
  rssStore.setSelectedArticle(article.id);
  router.push(`/article/${article.id}`);
};

/**
 * 处理搜索
 */
const handleSearch = () => {
  rssStore.updateSearchFilter({ keyword: searchKeyword.value });
};

/**
 * 刷新RSS源
 */
const handleRefresh = async () => {
  try {
    isRefreshing.value = true;
    await rssStore.refreshAllFeeds();
  } catch (error) {
    console.error('刷新失败:', error);
  } finally {
    isRefreshing.value = false;
  }
};

/**
 * 切换文章收藏状态
 * @param {Event} event - 事件对象
 * @param {string} articleId - 文章ID
 */
const toggleFavorite = async (event: Event, articleId: string) => {
  event.stopPropagation();
  try {
    await rssStore.toggleArticleFavorite(articleId);
  } catch (error) {
    console.error('切换收藏状态失败:', error);
  }
};

/**
 * 格式化时间
 * @param {Date} date - 日期对象
 * @returns {string} 格式化后的时间字符串
 */
const formatTime = (date: Date): string => {
  // 确保输入是有效的Date对象
  if (!date || !(date instanceof Date) || isNaN(date.getTime())) {
    return '未知时间';
  }
  
  const now = new Date();
  const diff = now.getTime() - date.getTime();
  const minutes = Math.floor(diff / (1000 * 60));
  const hours = Math.floor(diff / (1000 * 60 * 60));
  const days = Math.floor(diff / (1000 * 60 * 60 * 24));
  
  if (minutes < 1) {
    return '刚刚';
  } else if (minutes < 60) {
    return `${minutes}分钟前`;
  } else if (hours < 24) {
    return `${hours}小时前`;
  } else {
    return `${days}天前`;
  }
};

/**
 * 导航到订阅管理页
 */
const goToSubscriptions = () => {
  router.push('/subscriptions');
};

/**
 * 导航到设置页
 */
const goToSettings = () => {
  router.push('/settings');
};

// 组件挂载时初始化数据
onMounted(async () => {
  try {
    await rssStore.initialize();
  } catch (error) {
    console.error('初始化失败:', error);
  }
});
</script>

<template>
  <div class="min-h-screen bg-gradient-to-br from-blue-50 via-white to-blue-50">
    <!-- 顶部导航栏 -->
    <header class="sticky top-0 z-50 bg-white/80 backdrop-blur-md border-b border-blue-100 shadow-sm">
      <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div class="flex items-center justify-between h-16">
          <!-- Logo和标题 -->
          <div class="flex items-center space-x-3">
            <div class="w-10 h-10 bg-gradient-to-br from-blue-400 to-blue-600 rounded-xl flex items-center justify-center shadow-lg">
              <BookOpen class="w-6 h-6 text-white" />
            </div>
            <div>
              <h1 class="text-xl font-bold text-gray-900">RSS阅读器</h1>
              <p class="text-sm text-gray-500">{{ unreadCount }} 篇未读</p>
            </div>
          </div>
          
          <!-- 操作按钮 -->
          <div class="flex items-center space-x-3">
            <button
              @click="handleRefresh"
              :disabled="isRefreshing"
              class="p-2 text-gray-600 hover:text-blue-600 hover:bg-blue-50 rounded-lg transition-all duration-200 disabled:opacity-50"
              title="刷新"
            >
              <RefreshCw :class="['w-5 h-5', { 'animate-spin': isRefreshing }]" />
            </button>
            
            <button
              @click="goToSubscriptions"
              class="p-2 text-gray-600 hover:text-blue-600 hover:bg-blue-50 rounded-lg transition-all duration-200"
              title="订阅管理"
            >
              <Plus class="w-5 h-5" />
            </button>
            
            <button
              @click="goToSettings"
              class="p-2 text-gray-600 hover:text-blue-600 hover:bg-blue-50 rounded-lg transition-all duration-200"
              title="设置"
            >
              <Settings class="w-5 h-5" />
            </button>
          </div>
        </div>
      </div>
    </header>

    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-6">
      <div class="grid grid-cols-1 lg:grid-cols-4 gap-6">
        <!-- 左侧边栏 - RSS源列表 -->
        <div class="lg:col-span-1">
          <div class="bg-white/70 backdrop-blur-sm rounded-2xl shadow-lg border border-blue-100 p-6">
            <h2 class="text-lg font-semibold text-gray-900 mb-4">RSS源</h2>
            
            <!-- 全部文章选项 -->
            <button
              @click="handleFeedSelect(null)"
              :class="[
                'w-full text-left p-3 rounded-xl transition-all duration-200 mb-2',
                !rssStore.selectedFeedId
                  ? 'bg-blue-100 text-blue-700 shadow-md'
                  : 'hover:bg-blue-50 text-gray-700'
              ]"
            >
              <div class="flex items-center justify-between">
                <span class="font-medium">全部文章</span>
                <span class="text-sm bg-blue-200 text-blue-700 px-2 py-1 rounded-full">
                  {{ rssStore.articles.length }}
                </span>
              </div>
            </button>
            
            <!-- RSS源列表 -->
            <div class="space-y-2">
              <button
                v-for="feed in rssStore.feeds"
                :key="feed.id"
                @click="handleFeedSelect(feed.id)"
                :class="[
                  'w-full text-left p-3 rounded-xl transition-all duration-200',
                  rssStore.selectedFeedId === feed.id
                    ? 'bg-blue-100 text-blue-700 shadow-md'
                    : 'hover:bg-blue-50 text-gray-700'
                ]"
              >
                <div class="flex items-center justify-between">
                  <div class="flex-1 min-w-0">
                    <p class="font-medium truncate">{{ feed.title }}</p>
                    <p class="text-sm text-gray-500 truncate">{{ feed.description }}</p>
                  </div>
                  <div class="ml-2 flex flex-col items-end">
                    <span class="text-sm bg-gray-200 text-gray-700 px-2 py-1 rounded-full">
                      {{ feed.articleCount }}
                    </span>
                    <span v-if="feed.unreadCount > 0" class="text-xs bg-red-100 text-red-700 px-2 py-1 rounded-full mt-1">
                      {{ feed.unreadCount }}
                    </span>
                  </div>
                </div>
              </button>
            </div>
            
            <!-- 加载状态 -->
            <div v-if="rssStore.feedsLoading" class="text-center py-4">
              <div class="inline-block animate-spin rounded-full h-6 w-6 border-b-2 border-blue-600"></div>
              <p class="text-sm text-gray-500 mt-2">加载中...</p>
            </div>
          </div>
        </div>

        <!-- 主内容区域 -->
        <div class="lg:col-span-3">
          <!-- 搜索栏 -->
          <div class="bg-white/70 backdrop-blur-sm rounded-2xl shadow-lg border border-blue-100 p-6 mb-6">
            <div class="relative">
              <Search class="absolute left-3 top-1/2 transform -translate-y-1/2 w-5 h-5 text-gray-400" />
              <input
                v-model="searchKeyword"
                @input="handleSearch"
                type="text"
                placeholder="搜索文章标题、内容或作者..."
                class="w-full pl-10 pr-4 py-3 bg-blue-50/50 border border-blue-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all duration-200"
              />
            </div>
          </div>

          <!-- 文章列表 -->
          <div class="space-y-4">
            <!-- 当前RSS源信息 -->
            <div v-if="selectedFeed" class="bg-white/70 backdrop-blur-sm rounded-2xl shadow-lg border border-blue-100 p-4">
              <div class="flex items-center space-x-3">
                <div class="w-12 h-12 bg-gradient-to-br from-blue-400 to-blue-600 rounded-xl flex items-center justify-center">
                  <BookOpen class="w-6 h-6 text-white" />
                </div>
                <div>
                  <h3 class="font-semibold text-gray-900">{{ selectedFeed.title }}</h3>
                  <p class="text-sm text-gray-500">{{ selectedFeed.description }}</p>
                </div>
              </div>
            </div>

            <!-- 文章卡片列表 -->
            <div v-if="!rssStore.articlesLoading" class="space-y-4">
              
              <article
                v-for="article in filteredArticles"
                :key="article.id"
                @click="handleArticleClick(article)"
                class="bg-white/70 backdrop-blur-sm rounded-2xl shadow-lg border border-blue-100 p-6 cursor-pointer transition-all duration-300 hover:shadow-xl hover:-translate-y-1 hover:bg-white/90"
              >
                <div class="flex items-start justify-between">
                  <div class="flex-1 min-w-0">
                    <!-- 文章标题 -->
                    <h3 :class="[
                      'text-lg font-semibold mb-2 line-clamp-2',
                      article.isRead ? 'text-gray-600' : 'text-gray-900'
                    ]">
                      {{ article.title }}
                    </h3>
                    
                    <!-- 文章摘要 -->
                    <p v-if="article.summary" class="text-gray-600 text-sm mb-3 line-clamp-3">
                      {{ article.summary }}
                    </p>
                    
                    <!-- 文章元信息 -->
                    <div class="flex items-center space-x-4 text-sm text-gray-500">
                      <span v-if="article.author" class="flex items-center space-x-1">
                        <span>{{ article.author }}</span>
                      </span>
                      
                      <span class="flex items-center space-x-1">
                        <Clock class="w-4 h-4" />
                        <span>{{ formatTime(article.publishedAt) }}</span>
                      </span>
                      
                      <span v-if="!article.isRead" class="bg-blue-100 text-blue-700 px-2 py-1 rounded-full text-xs">
                        未读
                      </span>
                    </div>
                  </div>
                  
                  <!-- 操作按钮 -->
                  <div class="ml-4 flex flex-col items-end space-y-2">
                    <button
                      @click="toggleFavorite($event, article.id)"
                      :class="[
                        'p-2 rounded-lg transition-all duration-200',
                        article.isFavorite
                          ? 'text-yellow-600 bg-yellow-50 hover:bg-yellow-100'
                          : 'text-gray-400 hover:text-yellow-600 hover:bg-yellow-50'
                      ]"
                      title="收藏"
                    >
                      <Star :class="['w-5 h-5', { 'fill-current': article.isFavorite }]" />
                    </button>
                  </div>
                </div>
              </article>
            </div>

            <!-- 加载状态 -->
            <div v-if="rssStore.articlesLoading" class="text-center py-12">
              <div class="inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"></div>
              <p class="text-gray-500 mt-4">加载文章中...</p>
            </div>

            <!-- 空状态 -->
            <div v-if="!rssStore.articlesLoading && filteredArticles.length === 0" class="text-center py-12">
              <div class="w-24 h-24 bg-gray-100 rounded-full flex items-center justify-center mx-auto mb-4">
                <BookOpen class="w-12 h-12 text-gray-400" />
              </div>
              <h3 class="text-lg font-medium text-gray-900 mb-2">暂无文章</h3>
              <p class="text-gray-500 mb-6">
                {{ searchKeyword ? '没有找到匹配的文章' : '还没有订阅任何RSS源' }}
              </p>
              <button
                v-if="!searchKeyword"
                @click="goToSubscriptions"
                class="inline-flex items-center px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors duration-200"
              >
                <Plus class="w-4 h-4 mr-2" />
                添加RSS源
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
/* 文本截断样式 */
.line-clamp-2 {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.line-clamp-3 {
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

/* 自定义滚动条 */
::-webkit-scrollbar {
  width: 6px;
}

::-webkit-scrollbar-track {
  background: #f1f5f9;
  border-radius: 3px;
}

::-webkit-scrollbar-thumb {
  background: #cbd5e1;
  border-radius: 3px;
}

::-webkit-scrollbar-thumb:hover {
  background: #94a3b8;
}
</style>
